package org.cloud.framework.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.CompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;

import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;

//import de.innosystec.unrar.Archive;
//import de.innosystec.unrar.rarfile.FileHeader;


/**
 * 文件工具类
 *
 */
public class FileTool {
    private static final Logger log = Logger.getLogger(FileTool.class);
    
    /**
     * 创建目录
     * 
     * @param dir 目录
     */
    public static void mkdir(String dir) {
        try {
            String dirTemp = dir;
            File dirPath = new File(dirTemp);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
        } catch (Exception e) {
            log.error("创建目录操作出错: "+e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 新建文件
     * 
     * @param fileName
     *            String 包含路径的文件名 如:E:\phsftp\src\123.txt
     * @param content
     *            String 文件内容
     *            
     */
    public static void createNewFile(String fileName, String content) {
        try {
            String fileNameTemp = fileName;
            File filePath = new File(fileNameTemp);
            if (!filePath.exists()) {
                filePath.createNewFile();
            }
            FileWriter fw = new FileWriter(filePath);
            PrintWriter pw = new PrintWriter(fw);
            String strContent = content;
            pw.println(strContent);
            pw.flush();
            pw.close();
            fw.close();
        } catch (Exception e) {
            log.error("新建文件操作出错: "+e.getMessage());
            e.printStackTrace();
        }

    }
    
    /**
     * 删除文件
     * 
     * @param fileName 包含路径的文件名
     */
    public static void delFile(String fileName) {
        try {
            String filePath = fileName;
            File delFile = new File(filePath);
            delFile.delete();
        } catch (Exception e) {
            log.error("删除文件操作出错: "+e.getMessage());
            e.printStackTrace();
        }
    }
    

    /**
     * 删除文件夹
     * 
     * @param folderPath  文件夹路径
     */
    public static void delFolder(String folderPath) {
        try {
            // 删除文件夹里面所有内容
            delAllFile(folderPath); 
            String filePath = folderPath;
            File myFilePath = new File(filePath);
            // 删除空文件夹
            myFilePath.delete(); 
        } catch (Exception e) {
            log.error("删除文件夹操作出错"+e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 删除文件夹里面的所有文件
     * 
     * @param path 文件夹路径
     */
    public static void delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] childFiles = file.list();
        File temp = null;
        for (int i = 0; i < childFiles.length; i++) {
            //File.separator与系统有关的默认名称分隔符
            //在UNIX系统上，此字段的值为'/'；在Microsoft Windows系统上，它为 '\'。
            if (path.endsWith(File.separator)) {
                temp = new File(path + childFiles[i]);
            } else {
                temp = new File(path + File.separator + childFiles[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + childFiles[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + childFiles[i]);// 再删除空文件夹
            }
        }
    }

    
    /**
     * 复制单个文件
     * 
     * @param srcFile
     *            包含路径的源文件 如：E:/phsftp/src/abc.txt
     * @param dirDest
     *            目标文件目录；若文件目录不存在则自动创建  如：E:/phsftp/dest
     * @throws IOException
     */
    public static void copyFile(String srcFile, String dirDest) {
        try {
            FileInputStream in = new FileInputStream(srcFile);
            mkdir(dirDest);
            FileOutputStream out = new FileOutputStream(dirDest+"/"+new File(srcFile).getName());
            int len;
            byte buffer[] = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (Exception e) {
            log.error("复制文件操作出错:"+e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 复制文件夹
     * 
     * @param oldPath
     *            String 源文件夹路径 如：E:/phsftp/src
     * @param newPath
     *            String 目标文件夹路径 如：E:/phsftp/dest
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath) {
        try {
            // 如果文件夹不存在 则新建文件夹
            mkdir(newPath);
            File file = new File(oldPath);
            String[] files = file.list();
            File temp = null;
            for (int i = 0; i < files.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + files[i]);
                } else {
                    temp = new File(oldPath + File.separator + files[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath
                            + "/" + (temp.getName()).toString());
                    byte[] buffer = new byte[1024 * 2];
                    int len;
                    while ((len = input.read(buffer)) != -1) {
                        output.write(buffer, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {// 如果是子文件夹
                    copyFolder(oldPath + "/" + files[i], newPath + "/" + files[i]);
                }
            }
        } catch (Exception e) {
            log.error("复制文件夹操作出错:"+e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 移动文件到指定目录
     * 
     * @param oldPath 包含路径的文件名 如：E:/phsftp/src/ljq.txt
     * @param newPath 目标文件目录 如：E:/phsftp/dest
     */
    public static void moveFile(String oldPath, String newPath) {
        copyFile(oldPath, newPath);
        delFile(oldPath);
    }
    
    /**
     * 移动文件夹里内容到指定目录，不会删除文件夹
     * 
     * @param oldPath 源文件目录  如：E:/phsftp/src
     * @param newPath 目标文件目录 如：E:/phsftp/dest
     */
    public static void moveFiles(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delAllFile(oldPath);
    }
    
    /**
     * 移动文件夹到指定目录，会删除文件夹
     * 
     * @param oldPath 源文件目录  如：E:/phsftp/src
     * @param newPath 目标文件目录 如：E:/phsftp/dest
     */
    public static void moveFolder(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }
    
    /**
     * 解压zip格式压缩包 
     * 对应的是ant.jar
     */
    public static String unzip(String sourceZip,String destDir, boolean b){
    	String path = "";
        try{
        	File input = new File(sourceZip);
            Project p = new Project();
            Expand e = new Expand();
            e.setProject(p);
            e.setSrc(input);
            e.setOverwrite(false);
            if(b){
            	path = destDir;
            }else{
            	path = destDir + input.getName().substring(0, input.getName().length()-4);
            }
            e.setDest(new File(path));  
            /*
            ant下的zip工具默认压缩编码为UTF-8编码， 而winRAR软件压缩是用的windows默认的GBK或者GB2312编码 所以解压缩时要制定编码格式 
            */
            e.setEncoding("gbk");
            e.execute();
        }catch(Exception e){
           e.printStackTrace();
           path = "";
        }
        return path;
    }
    /**
     * 解压rar格式压缩包。
     * 对应的是java-unrar-0.3.jar，但是java-unrar-0.3.jar又会用到commons-logging-1.1.1.jar
     */
    private static String unrar(String sourceRar,String destDir, boolean b){
    	String path = "";
        Archive a = null;
        FileOutputStream fos = null;
        try{
        	File input = new File(sourceRar);
            a = new Archive(input);
            FileHeader fh = a.nextFileHeader();
            while(fh!=null){
                if(!fh.isDirectory()){
                    //1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
                    String compressFileName = "";
                    String destFileName = "";
                    String destDirName = "";
                    if(fh.isUnicode()){
                    	compressFileName = fh.getFileNameW().trim();
                    }else{
                    	compressFileName = fh.getFileNameString().trim();
                    }
                    if(b){
                    	path = destDir;
                    }else{
                    	path = destDir + input.getName().substring(0, input.getName().length()-4) + "/";
                    }
                    //非windows系统 
                    if(File.separator.equals("/")){
	                	destFileName = path + compressFileName.replaceAll("\\\\", "/");
	                    destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
                    //windows系统  
                    }else{
                        destFileName = path + compressFileName.replaceAll("/", "\\\\");
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
                    }
                    //2创建文件夹
                    File dir = new File(destDirName);
                    if(!dir.exists()||!dir.isDirectory()){
                        dir.mkdirs();
                    }
                    //3解压缩文件
                    fos = new FileOutputStream(new File(destFileName));
                    a.extractFile(fh, fos);
                    fos.close();
                    fos = null;
                }
                fh = a.nextFileHeader();
            }    
            a.close();
            a = null;
        }catch(Exception e){
           e.printStackTrace();
           path = "";
        }finally{
            if(fos!=null){    
                try{fos.close();fos=null;}catch(Exception e){e.printStackTrace();}
            }
            if(a!=null){
                try{a.close();a=null;}catch(Exception e){e.printStackTrace();}
            }    
        }
        return path;
    }
    /**
     * 解压.7z格式压缩包。
     * @param sourceFile
     * @param destDir
     * @param b 是否解压到本地当前文件加 b=true解压到当前文件夹，b=false解压到目录下
     * @return
     */
    private static String un7Z(String sourceFile, String destDir,boolean b){
    	String path = "";
    	try {
    		File input = new File(sourceFile);
            SevenZFile sevenZFile = new SevenZFile(input);
            SevenZArchiveEntry entry = sevenZFile.getNextEntry();
            while (entry != null) {
                if (entry.isDirectory()) {
                	if(b){
                		path = destDir;
                	}else{
                		path = destDir + input.getName().substring(0, input.getName().length()-3) + "/";
                	}
                    new File(path + entry.getName()).mkdirs();
                    entry = sevenZFile.getNextEntry();
                    continue;
                }
                if(b){
                	path = destDir;
                }else{
                	path = destDir + input.getName().substring(0, input.getName().length()-3);
                }
                new File(path).mkdir();
                FileOutputStream out = new FileOutputStream(path + File.separator + entry.getName());
                byte[] content = new byte[(int) entry.getSize()];
                sevenZFile.read(content, 0, content.length);
                out.write(content);
                out.close();
                entry = sevenZFile.getNextEntry();
            }
            sevenZFile.close();
		} catch (Exception e) {
			e.printStackTrace();
			path="";
		}
    	return path;
    }
    /**
     * 解压.tar格式压缩包。  
     * @param sourceFile
     * @param destDir
     * @param b 是否解压到本地当前文件加 b=true解压到当前文件夹，b=false解压到目录下
     * @return
     */
    private static String untar(String sourceFile, String destDir, boolean b) {  
        String path = "";  
        OutputStream out = null;  
        try { 
        	File input = new File(sourceFile);
            TarInputStream in = new TarInputStream(new FileInputStream(input),"gbk");  
            TarEntry entry = null;  
            while ((entry = in.getNextEntry()) != null) {  
                if (entry.isDirectory()) {  
                    continue;  
                }
                if(b){//解压到当前
                	path = destDir;
                }else{//解压到目录下
                	path = destDir + input.getName().substring(0, input.getName().length()-4);
                }
                File outfile = new File(path,entry.getName());
                new File(outfile.getParent()).mkdirs();  
                out = new BufferedOutputStream(new FileOutputStream(outfile));  
                int x = 0;  
                while ((x = in.read()) != -1) {  
                    out.write(x);  
                }  
                out.close();  
            }  
            in.close();  
        } catch (IOException ioe) {  
            ioe.printStackTrace();  
            path = "";  
        }  
        return path;  
    }
	/**
	 * 
	 * @param sourceFile
	 * @param destDir
	 * @param b 是否解压到本地当前文件加 b=true解压到当前文件夹，b=false解压到目录下
	 * @return
	 * @throws Exception
	 */
	public static String untGzip(String sourceFile, String destDir,boolean b) throws Exception {
		String path="";
		try {
			File input = new File(sourceFile);
			InputStream is = new FileInputStream(input);
			CompressorInputStream in;
			in = new GzipCompressorInputStream(is, true);
			TarArchiveInputStream tin = new TarArchiveInputStream(in,"gbk");
			TarArchiveEntry entry = tin.getNextTarEntry();
			while (entry != null) {
				if(b){//解压到当前目录
					path = destDir;
				}else{//解压到目录下
					path = destDir + input.getName().substring(0, input.getName().length()-7);
				}
				File archiveEntry = new File(path, entry.getName());
				archiveEntry.getParentFile().mkdirs();
				if (entry.isDirectory()) {
					archiveEntry.mkdir();
					entry = tin.getNextTarEntry();
					continue;
				}
				OutputStream out = new FileOutputStream(archiveEntry);
				IOUtils.copy(tin, out);
				out.close();
				entry = tin.getNextTarEntry();
			}
			in.close();
			tin.close();
		} catch (Exception e) {
			e.printStackTrace();
			path = "";
		}
		return path;
	}
    /**
     * 解压缩  总接口，zip、rar、7z、tar、tar.gz   
     * @param sourceFile
     * @param destDir
     * @param b  是否解压到目标当前文件夹下， b=true解压到目标当前文件夹下，b=false解压到目标当前文件夹下的 压缩包名文件夹下
     * @return
     * @throws Exception
     */
    public static String deCompress(String sourceFile,String destDir,boolean b) throws Exception{    
        //保证文件夹路径最后是"/"或者"\"    
        char lastChar = destDir.charAt(destDir.length()-1);    
        if(lastChar!='/'&&lastChar!='\\'){    
            destDir += File.separator;    
        }    
        //根据类型，进行相应的解压缩    
        String type = sourceFile.substring(sourceFile.lastIndexOf(".")+1);    
        if(type.equals("zip")){    
            return unzip(sourceFile, destDir,b);    
         }else if(type.equals("rar")){    
        	return unrar(sourceFile, destDir,b);    
         }else if(type.equals("7z")){
        	return un7Z(sourceFile, destDir,b);
         }else if(type.equals("tar")){
        	return untar(sourceFile, destDir,b);
         }else if(type.equals("gz")){
        	return untGzip(sourceFile, destDir,b);
         }else{    
             return "";  
         }    
     }
    /**
     * 递归解压
     * @param sourceFile
     * @param destDir
     * @param b
     * @throws Exception 
     */
    public static void recursiveDecompression(String sourceFile) throws Exception{
    	File input = new File(sourceFile);
    	if(input.isFile()){
    		if(isCompressedFile(sourceFile)){
    			 if(File.separator.equals("/")){
    				 deCompress(sourceFile, sourceFile.substring(0, sourceFile.lastIndexOf("/")), false);
    				 recursiveDecompression(getPath(sourceFile));
    			 }else{
    				 deCompress(sourceFile, sourceFile.substring(0, sourceFile.lastIndexOf("\\")), false);
    				 recursiveDecompression(getPath(sourceFile));
    			 }
    			
    		}
    	}else if(input.isDirectory()){
    		File[] listFiles = input.listFiles();
    		for (File file : listFiles) {
				recursiveDecompression(file.getAbsolutePath());
			}
    	}else{
    		System.out.println("不存在:"+sourceFile);
    	}
    }
    /**
     * 判断是否为压缩文件
     * @param sourceFile
     * @return
     */
    private static Boolean isCompressedFile(String sourceFile){
    	 String type = sourceFile.substring(sourceFile.lastIndexOf(".")+1);    
    	if(type.equals("zip") || type.equals("rar") || 
    			type.equals("7z") || type.equals("tar") || 
    			type.equals("gz")){
    		return true;
    	}else{
    		return false;
    	}
    }
    /**
     * 获取去路径
     * @param sourceFile
     * @return
     */
    private static String getPath(String sourceFile){
    	String type = sourceFile.substring(sourceFile.lastIndexOf(".")+1);    
    	if(type.equals("zip")){
    		return sourceFile.substring(0, sourceFile.length()-4);
    	}else if(type.equals("rar")){
    		return sourceFile.substring(0, sourceFile.length()-4);
    	}else if(type.equals("7z")){
    		return sourceFile.substring(0, sourceFile.length()-3);
    	}else if(type.equals("tar")){
    		return sourceFile.substring(0, sourceFile.length()-4);
    	}else if(type.equals("gz")){
    		return sourceFile.substring(0, sourceFile.length()-7);
    	}else{
    		return "";
    	}
    }
    
    /**
     * 压缩文件
     * 
     * @param srcDir
     *            压缩前存放的目录
     * @param destDir
     *            压缩后存放的目录
     * @throws Exception
     */
    public static void yaSuoZip(String srcDir, String destDir) throws Exception {
        String tempFileName=null;
        byte[] buf = new byte[1024*2];
        int len;
        //获取要压缩的文件
        File[] files = new File(srcDir).listFiles();
        if(files!=null){
            for (File file : files) {
                if(file.isFile()){
                    FileInputStream fis = new FileInputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    if (destDir.endsWith(File.separator)) {
                        tempFileName = destDir + file.getName() + ".zip";
                    } else {
                        tempFileName = destDir + "/" + file.getName() + ".zip";
                    }
                    FileOutputStream fos = new FileOutputStream(tempFileName);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    ZipOutputStream zos = new ZipOutputStream(bos);// 压缩包
                    ZipEntry ze = new ZipEntry(file.getName());// 压缩包文件名
                    zos.putNextEntry(ze);// 写入新的ZIP文件条目并将流定位到条目数据的开始处
                    while ((len = bis.read(buf)) != -1) {
                        zos.write(buf, 0, len);
                        zos.flush();
                    }
                    bis.close();
                    zos.close();
                
                }
            }
        }
    }
    
    
    /**
     * 读取数据
     * 
     * @param inSream
     * @param charsetName
     * @return
     * @throws Exception
     */
    public static String readData(InputStream inSream, String charsetName) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while( (len = inSream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inSream.close();
        return new String(data, charsetName);
    }
    
    /**
     * 一行一行读取文件，适合字符读取，若读取中文字符时会出现乱码
     * 
     * @param path
     * @return
     * @throws Exception
     */
    public static Set<String> readFile(String path) throws Exception{
        Set<String> datas=new HashSet<String>();
        FileReader fr=new FileReader(path);
        BufferedReader br=new BufferedReader(fr);
        String line=null;
        while ((line=br.readLine())!=null) {
            datas.add(line);
        }
        br.close();
        fr.close();
        return datas;
    }
    
    /**
     * 递归文件夹
     * @param path
     * @return
     */
	public static List<String> directory(String path){
		File file = new File(path);
		List<String> l=new ArrayList<String>();
		if(file.isDirectory()){
			l.add(file.getAbsolutePath());
			File[] listFiles = file.listFiles();
			for (File file2 : listFiles) {
				l.addAll(directory(file2.getAbsolutePath()));
			}
		}
		return l;
	}
	/**
	 * 加入 当前目录
	 * @param path
	 * @return
	 */
	public static List<String> directories(String path){
		List<String> l=new ArrayList<String>();
		l.add(path);
		l.addAll(directory(path));
		List<String> l2=new ArrayList<String>();
		for (int i = l.size()-1; i > 0; i-- ) {
			l2.add(l.get(i));
		}
		return l2;
	}
	/**
	 * 压缩 文件夹 zip
	 * @param inputFileName
	 * @param zipFileName
	 * @throws Exception
	 */
    public static void zip(String inputFileName,String zipFileName) throws Exception {
        inputFileName=inputFileName.replace("\\", "/");
       // String basedir=inputFileName.substring(inputFileName.lastIndexOf("/")+1, inputFileName.length());
        zip(zipFileName, new File(inputFileName),"");
    }

    private static void zip(String zipFileName, File inputFile,String basedir) throws Exception {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
        zip(out, inputFile, basedir);
        System.out.println(inputFile.getAbsolutePath()+".zip done");
        out.close();
    }

    private static void zip(ZipOutputStream out, File f, String base) throws Exception {
        if (f.isDirectory()) {
           File[] fl = f.listFiles();
           out.putNextEntry(new ZipEntry(base + "/"));
           base = base.length() == 0 ? "" : base + "/";
           for (int i = 0; i < fl.length; i++) {
           zip(out, fl[i], base + fl[i].getName());
         }
        }else {
           out.putNextEntry(new ZipEntry(base));
           FileInputStream in = new FileInputStream(f);
           int b;
           byte[] by = new byte[1024];
           while ((b = in.read(by)) != -1) {
        	   out.write(by, 0, b);
           }
          out.flush();
          in.close();
       }
    }
    public static void main(String[] args) throws Exception {
    	String sourcePath="D:\\Users\\anhuifeng\\Volumes\\root\\backup\\1527053928956\\file";
    	String targetPath="D:\\Users\\anhuifeng\\Volumes\\root\\temp\\file";

/*
    	List<String> l = directories(sourcePath);
		for (int i = 0; i < l.size(); i++ ) {
			zip(l.get(i), "D:\\Users\\anhuifeng\\Volumes\\root\\package/package/abc.zip");
			//FileTool.delFolder(l.get(i));
		}
		*/
		//unzip("D:\\Users\\anhuifeng\\Volumes\\root\\package\\package\\abc.zip","D:\\Users\\anhuifeng\\Volumes\\root\\package\\package\\",false);
        if(!new File(targetPath).exists()){
            new File(targetPath).mkdirs();
        }
        copyFolder(sourcePath,targetPath);


        //delAllFile(sourcePath);
	}
}
